import AsyncStorage from '@react-native-community/async-storage';

import Log from '../common/log';
import {
  DEVICE_ID,
  GRAY_USE_RN_VIDEO,
  GRAY_NOT_USE_BIG_CHANNEL,
  STORAGE_KEY_GRAY,
  GRAY_NEED_MANUAL_SIGN_IN
} from '../constant';

export interface GrayRow {
  name: string;
  key: string;
  list: string[];
  full: boolean;
}

const TAG = 'Gray';

let grayList: GrayRow[] = [];

AsyncStorage.getItem(STORAGE_KEY_GRAY).then((res: any): void => {
  if (res) {
    try {
      grayList = JSON.parse(res);
    } catch (error) {
      console.error('Gray parse error : ', error);
    }
  }
});

export const setGrayList = (list: GrayRow[]): void => {
  grayList = list;

  Log.i(
    TAG,
    JSON.stringify({
      event: 'setGrayList',
      list
    })
  );
  AsyncStorage.setItem(STORAGE_KEY_GRAY, JSON.stringify(list));
};

export const getGrayList = (): GrayRow[] => grayList;

const getUseStatusWithKey = (key: string): boolean => {
  try {
    const gray = grayList.find((g): boolean => g.key === key);
    if (!gray) return false;

    if (gray.full) {
      return true;
    }

    const use = !!gray.list.find((deviceId): boolean => deviceId === DEVICE_ID);
    return use;
  } catch (error) {
    return false;
  }
};

export const getUseRnVideo = (): boolean =>
  getUseStatusWithKey(GRAY_USE_RN_VIDEO);

export const getNotUseBigChannel = (): boolean =>
  getUseStatusWithKey(GRAY_NOT_USE_BIG_CHANNEL);

export const getNeedManualSignIn = (): boolean =>
  getUseStatusWithKey(GRAY_NEED_MANUAL_SIGN_IN);
